﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Rose.Models;


namespace Rose.Helper
{
    public class AlbumHelpModel
    {
        private   Database_RoseEntities db = new Database_RoseEntities();
        #region 格式转化
        private   int FromBoolToInt(bool? isOnlyForFriend)
        {
            switch (isOnlyForFriend)
            {
                //null 表示自己
                //true 表示朋友
                //false 表示任何人
                case null: return 0;
                case true: return 1;
                case false: return 2;
                default: return 2;
            }
        }

        private    bool? FromIntToBool(int isOnlyForFriend)
        {
            switch (isOnlyForFriend)
            {
                case 0: return null;
                case 1: return true;
                default: return false;
            }
        }

        #endregion

        #region 获取albumModel
        private  AlbumModel ChangeAlbumToAlbumModel(Album album)
        {

            return new AlbumModel()
            {
                ImagePath = album.ImagePath,
                Title = album.Title,
                PhotoCount = album.PhotoCount,
                IsOnlyForFriend = FromBoolToInt(album.IsOnlyForFriend),
                AlbumId=album.Id.ToString()

            };
        }
        private  List<AlbumModel> ChangeAlbumsToAlbumModels(List<Album> albums)
        {
            List<AlbumModel> returnModel = new List<AlbumModel>();
            foreach (var item in albums)
            {
                returnModel.Add(ChangeAlbumToAlbumModel(item));
            }
            return returnModel;

        }

        private  List<Album> GetAlbums(string selfId, bool? isOnlyForFriend)
        {
            switch (isOnlyForFriend)
            {
                    //null 表示自己
                    //true 表示朋友
                    //false 表示任何人
                case null: return db.Albums.Where(c => c.UserId == selfId).OrderBy(c=>c.CreateTime).ToList();
                case true: return db.Albums.Where(c => c.UserId == selfId && c.IsOnlyForFriend != null).OrderBy(c=>c.CreateTime).ToList();
                default: return db.Albums.Where(c => c.UserId == selfId && c.IsOnlyForFriend == false).OrderBy(c=>c.CreateTime).ToList();
            }
        }

        public  List<AlbumModel> GetAlbumModels(string selfId, bool? isOnlyForFriend)
        {
            return ChangeAlbumsToAlbumModels(GetAlbums(selfId,isOnlyForFriend));
        }

        #endregion

        #region  更改相册信息
        
        
        public  bool ChangeAlbumLimit(string albumId, string selfId, int isOnlyForFriend)
        {
            Album album = db.Albums.Where(c => c.Id == new Guid(albumId) && c.UserId == selfId).FirstOrDefault();
            if (album == null)
                return false;
            try
            {
                album.IsOnlyForFriend = FromIntToBool(isOnlyForFriend);
                db.SaveChanges();
                return true;
            }
            catch
            { return false; }
        }

        public bool ChangeAlbum(string title, int isOnlyForFriend, string selfId,string albumId)
        {
            Album album = db.Albums.Where(c => c.Id == new Guid(albumId) && c.UserId == selfId).FirstOrDefault();
            if (album == null)
                return false;
            try
            {
                album.IsOnlyForFriend = FromIntToBool(isOnlyForFriend);
                album.Title = CheckDataHelpModel.CheckLength(title,50);
                db.SaveChanges();
                return true;
            }
            catch
            { return false; }
        }

        public  bool ChangeAlbumImagePath(string albumId, string selfId, string path)
        {
            Album album = db.Albums.Where(c => c.Id == new Guid(albumId) && c.UserId == selfId).FirstOrDefault();
            if (album == null)
                return false;
            try
            {
                album.ImagePath = path;
                db.SaveChanges();
                return true;
            }
            catch { return false; }
        }
        public bool ChangePhotoTitle(string selfId,string photoId, string title)
        {
            Photo model = db.Photos.Where(c => c.PhotoId == new Guid(photoId)).FirstOrDefault();
            if (model == null)
                return false;
            Album album = db.Albums.Where(c => c.Id == model.AlbumId).FirstOrDefault();
            if (album == null)
                return false;
            if (selfId != album.UserId)
                return false;
            try
            {
                model.Title = CheckDataHelpModel.CheckLength(title, 20);
                db.SaveChanges();
                return true;
            }
            catch
            {
                return true;
            }
        }

        #endregion

        #region  处理上传图片

        public  string  CreateAlbum(AlbumModel model,string selfId)
        {

            try
            {
                Album album = new Album()
                {
                    Id = Guid.NewGuid(),
                    UserId = selfId,
                    CreateTime = DateTime.Now,
                    Hit = 0,
                    IsOnlyForFriend = FromIntToBool(model.IsOnlyForFriend),
                    PhotoCount = 0,
                    Title = model.Title,
                    ImagePath = Rose.ViewRes.Defaultresx.DefaultAlbumPhoto
                    
                    //使用了默认路径
                };

                if (string.IsNullOrEmpty(album.Title))
                {
                    string name = new CheckHelpModel().CheckUserInfo(selfId).Name;
                    album.Title = name + Rose.ViewRes.Defaultresx.DefaultAlbumTitle;
                }
                db.AddToAlbums(album);
                db.SaveChanges();
                return album.Id.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
                
           
        }

        public  string UploadPhoto(string albumId,string extension)
        {

            Photo photo = new Photo()
            {
                AlbumId = new Guid(albumId),
                PhotoId = Guid.NewGuid(),
                Title=string.Empty
            };
            photo.Extension = extension;
            db.AddToPhotos(photo);
           
            
            ///begin updateAlbumCount
            Album album = db.Albums.Where(c => c.Id == photo.AlbumId).FirstOrDefault();
            if (album == null)
                throw new ArgumentNullException();
            album.PhotoCount += 1;

            if (album.LastUpload == null || DateTime.Now - album.LastUpload > new TimeSpan(0,10, 0))
            {   //保证不会有多个上传的动态
                new NewTrendHelpModel().AddAlbumTrend(photo, album.UserId);
            }

            UserInfo selfInfo = db.UserInfos.Where(c => c.Id == album.UserId).FirstOrDefault();
            if (selfInfo == null)
                throw new ArgumentNullException();

            if (selfInfo.PhotoCount == null)
            {
                selfInfo.PhotoCount = 0;
            }

            selfInfo.PhotoCount += 1;
            selfInfo.Score += int.Parse(Rose.ViewRes.Defaultresx.PhotoAddScore);

            album.LastUpload = DateTime.Now;


            db.SaveChanges();

            return photo.PhotoId.ToString() + "." + photo.Extension;
        }


        #endregion

        #region 某相册中的所有图片地址返回;
        public  List<PhotoModel> GetAlbumPhotos(string albumId,string userId)
        {

            var photos = db.Photos.Where(c => c.AlbumId == new Guid(albumId)).ToList();
            
            List<PhotoModel> returnModel = new List<PhotoModel>();
            foreach (var item in photos)
            {
                Photo addModel = db.Photos.Where(c => c.PhotoId ==item.PhotoId).FirstOrDefault();
                if (addModel == null)
                    continue;
                returnModel.Add(new PhotoModel() {
                    href = "/Photos/" + userId + "/" + albumId + "/"+addModel.PhotoId.ToString() + "." + addModel.Extension,
                    title=addModel.Title
                });
            }
            return returnModel;
        }

      

        #endregion

        #region  deletephoto and album
        public  bool DeletePhotoFromDatabase(string selfId ,string albumId, string photoId)
        {

            Photo photo = db.Photos.Where(c => c.PhotoId ==new Guid (photoId)).FirstOrDefault();
            if (photo == null)
                return true;
            Album album = db.Albums.Where(c => c.Id == new Guid(albumId) && c.UserId==selfId).FirstOrDefault();
            if (album == null)
                return false;
            try
            {
                album.PhotoCount -= 1;
                db.Photos.DeleteObject(photo);
                db.SaveChanges();
                return true;
            }
            catch { return false; }
        }

        public  bool  DeleteAlbumFromDatabase(string selfId, string albumId)
        {
            try
            {
                Album album = db.Albums.Where(c => c.UserId == selfId && c.Id == new Guid(albumId)).FirstOrDefault();
                db.Albums.DeleteObject(album);
                return true;
                //没有删除相片
            }
            catch
            {
                return false;
            }
        }


        ///photo  :/TempFile
        ///         /HeadImageFile
        ///         /Photos/zhanghao/albumId
        public    void  DeletePhotoFromFile(string locationFilePath )
        {
            if (!System.IO.File.Exists(locationFilePath))
                return ;
            try
            {
                System.IO.File.Delete(locationFilePath);
                return;
            }
            catch
            { return; }

        }

        public  void  DeletePhotoFromFile(string[] locationFilePaths)
        {
            foreach (string filepath in locationFilePaths)
            {
                try
                {
                    DeletePhotoFromFile(filepath);
                }
                catch
                {
                    continue;
                }

            }
            return;
        }


        #endregion

    }
}